package com.dsunsoft.rtu.web;

import com.dsunsoft.rtu.common.entity.RestCode;
import com.dsunsoft.rtu.common.entity.RestResult;
import com.dsunsoft.rtu.common.util.ConvertUtils;
import com.dsunsoft.rtu.common.vo.NgSelectVO;
import com.dsunsoft.rtu.core.base.BaseRestController;
import com.dsunsoft.rtu.dto.RtuDeviceRealInfoDto;
import com.dsunsoft.rtu.entity.HeartbeatInfo;
import com.dsunsoft.rtu.entity.RtuDevice;
import com.dsunsoft.rtu.netty.NettyHeartbeatMap;
import com.dsunsoft.rtu.query.RtuDeviceQuery;
import com.dsunsoft.rtu.service.RtuDeviceRealService;
import com.dsunsoft.rtu.service.RtuDeviceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/api/rtuDevice")
public class RtuDeviceController extends BaseRestController<RtuDevice, RtuDeviceQuery> {

    @Autowired
    private RtuDeviceService rtuDeviceService;
    @Autowired
    private RtuDeviceRealService rtuDeviceRealService;

    @PostMapping(value = "/heartbeat")
    public RestResult<List<HeartbeatInfo>> getDeviceHeartbeat(@RequestBody RtuDeviceQuery query) throws IOException {
        List<HeartbeatInfo> list = new ArrayList<>();
        if (StringUtils.isNotBlank(query.getDeviceId())) {
            HeartbeatInfo heartbeatInfo = NettyHeartbeatMap.get(ConvertUtils.toInteger(query.getDeviceId()));
            if (heartbeatInfo != null) {
                list.add(heartbeatInfo);
            }
        } else {
            Map<Integer, HeartbeatInfo> channelMap = NettyHeartbeatMap.get();
            for (Map.Entry<Integer, HeartbeatInfo> entry : channelMap.entrySet()) {
                list.add(entry.getValue());
            }
            if (!CollectionUtils.isEmpty(list)) {
                list = list.stream().sorted(Comparator.comparing(HeartbeatInfo::getLastReportDate).reversed())
                        .collect(Collectors.toList());
            }
        }
        return new RestResult<>(RestCode.SUCCESS, list);
    }

    @PostMapping(value = "/real")
    public RestResult<List<RtuDeviceRealInfoDto>> getReal(@RequestBody RtuDeviceQuery query) {
        List<RtuDeviceRealInfoDto> list = rtuDeviceRealService.getList(query);
        return new RestResult<>(RestCode.SUCCESS, list);
    }

    @PostMapping("/getSelect")
    public RestResult<List<NgSelectVO>> getSelect(@RequestBody RtuDeviceQuery query) {
        List<NgSelectVO> list = rtuDeviceService.getSelect(query);
        return new RestResult<>(RestCode.SUCCESS, list);
    }
}
